﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetDisk.Dtos;
using NetDisk.Models;
using NetDisk.ViewModels;
using Newtonsoft.Json;

namespace NetDisk.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DirsController : ControllerBase
    {
        private readonly ApplicationDbContext _dbContext;

        public DirsController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        [Authorize]
        [HttpPost]
        public int Create(CreateDirDto createDirDto)
        {
            using var trx = _dbContext.Database.BeginTransaction();
            var now = DateTimeOffset.Now.ToUnixTimeMilliseconds();
            var uploadDir = new UploadFile
            {
                FileName = Guid.NewGuid().ToString(),
                RealName = createDirDto.Name,
                ParentId = createDirDto.ParentId == 0 ? null : (int?)createDirDto.ParentId,
                IsDir = true,
                CreatedAt = now,
                UpdatedAt = now,
            };
            _dbContext.UploadFiles.Add(uploadDir);
            _dbContext.SaveChanges();

            var dirIndex = new DirIndex
            {
                DirId = uploadDir.Id,
                DirName = uploadDir.RealName,
                CreatedAt = now,
                UpdatedAt = now,
            };

            var parentIndex = new List<DirPathViewModel>
                {
                    new DirPathViewModel { Id = uploadDir.Id, Name = uploadDir.RealName }
                };
            GetPathIndex(uploadDir, parentIndex);
            dirIndex.DirPath = $"/{string.Join("/", parentIndex.Select(pIndex => pIndex.Name).Reverse().ToList())}/";
            parentIndex.Add(new DirPathViewModel { Id = 0, Name = "/" });
            dirIndex.ParentIndex = JsonConvert.SerializeObject(parentIndex);
            _dbContext.DirIndexes.Add(dirIndex);
            _dbContext.SaveChanges();

            trx.Commit();
            return uploadDir.Id;

        }

        private void GetPathIndex(UploadFile uploadDir, List<DirPathViewModel> ParentIndex)
        {
            if (uploadDir.ParentId != null)
            {
                var parentDir = _dbContext.UploadFiles
                    .Where(f => f.Id == uploadDir.ParentId)
                    .FirstOrDefault();
                if (parentDir != null)
                {
                    ParentIndex.Add(new DirPathViewModel { Id = uploadDir.ParentId.Value, Name = parentDir.RealName });
                    GetPathIndex(parentDir, ParentIndex);
                }
            }
        }
    }
}